<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <!-- :inline="true" 将表单放到一行 -->
        <el-form ref="searchForm" :inline="true" :model="searchForm" size="small">
          <el-form-item prop="name">
            <el-input v-model="searchForm.name" placeholder="用户名" />
          </el-form-item>
          <el-form-item prop="email">
            <el-input v-model="searchForm.email" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item prop="mobile">
            <el-input v-model="searchForm.mobile" placeholder="电话"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="goto(1)">搜索</el-button>
            <el-button type="danger" @click="resetSearch">重置</el-button>
            <el-button type="success" @click="addUser">添加</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-table
          :data="users"
          border
          style="width: 100%">
          <el-table-column
            prop="id"
            width="70"
            label="用户ID">
          </el-table-column>
          <el-table-column
            prop="name"
            width="80"
            label="用户名">
          </el-table-column>
          <el-table-column
            prop="department.name"
            label="部门名称">
          </el-table-column>
          <el-table-column
            label="角色">
            <template slot-scope="scope">
              {{scope.row.roles.map(r => r.remark).join(',')}}
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话">
          </el-table-column>
           <el-table-column
            width="70"
            label="状态">
            <template slot-scope="scope">
              <el-switch
                @change="changeStatus(scope.row.id, scope.row.status, scope.row.name)"
                :value="scope.row.status"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            width="190"
            label="操作">
             <template slot-scope="scope">
              <el-button icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)">编辑</el-button>
              <el-button icon="el-icon-delete" size="mini" @click="deleteById(scope.row.id)" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="float: right; margin-top: 10px;"
          background
          @current-change="goto"
          :current-page="current"
          :hide-on-single-page="true"
          layout="prev, pager, next"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <add-user-dialog @refresh="goto" :depts="depts" :roles="roles" ref="addDialog"></add-user-dialog>
    <edit-user-dialog @refresh="goto" :editUserForm="singleUser" :depts="depts" :roles="roles" ref="editDialog"></edit-user-dialog>
  </div>
</template>

<script>
import AddUserDialog from '@/components/SysUser/AddUserDialog.vue'
import EditUserDialog from '@/components/SysUser/EditUserDialog.vue'
import http from '@/utils/request'

export default {
  components: { AddUserDialog, EditUserDialog },
  data() {
    return {
      searchForm: {
        name: '',
        email: '',
        mobile: ''
      },
      singleUser: {},
      depts: [],
      roles: [],
      users: [],
      current: 1,
      total: 0
    }
  },
  mounted() {
    http.get('/department').then(res => {
      this.depts = res.data.data
    })
    http.get('/role').then(res => {
      this.roles = res.data.data
    })
    this.goto()
  },
  methods: {
    // 翻页
    goto(current = 1) {
      http.get('/sys-user', {
        params: {
          current: current,
          ...this.searchForm
        }
      }).then(res => {
         let datas = res.data.data
         this.users = datas.data
         this.current = datas.current
         this.total = datas.total
      })
    },
    // 重置
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.goto()
    },
    // 改变对应的用户状态
    changeStatus(id, status, name) {
       this.$confirm(`你是否要${status == 1 ? '禁用' : '启用'} ${name}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {  // 用户点击确认
           http.put(`/sys-user/${id}`, {
             status: status
           }).then(() => {
              http.get(`/sys-user/${id}`)
                .then(res => {
                  //为了避免前端整个表格全部重新渲染，我们只需要改变被改变的数据即可
                  let su = res.data.data
                  // 获取到数据对应的索引
                  let idx = this.users.findIndex(u => u.id == su.id)
                  // 将对应的数据替换掉，那么这个dom只会重新渲染当前行
                  this.users.splice(idx, 1, su)
                })
           })
        }).catch()  // 用户点击取消
    },
    // 添加
    addUser() {
      this.$refs.addDialog.$data.showAddUserDialog = true
    },
    editUser(id) {
      http.get(`/sys-user/e/${id}`)
        .then(res => {
           let su = res.data.data  // 获取到用户信息
           let {id, name, email, mobile} = su  // 解构出 id, name, email, mobile
           let roles = su.roles.map(r => r.id)   // 得到角色数组
           // 获取到部门的id数组
           let depts = this.getDeptsArray(su.department)
           let newSu = {id, name, email, mobile, roles, depts}
           this.singleUser = newSu
           this.$refs.editDialog.$data.showEditUserDialog = true
        })
    },
    deleteById(id) {
      console.log(id)
    },
    getDeptsArray(dept) {
      let arr = []
      while(dept) {
        arr.push(dept.id)
        dept = dept.parent
      }
      return arr.reverse()   // 数组翻转
    }
  }
}
</script>
<style>

</style>